import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';

import 'src/esp_device.dart';

export 'src/esp_blufi_code.dart';
export 'src/esp_device.dart';

class EspBlufi {
  EspBlufi._();

  final methodChannel = const MethodChannel('esp_blufi');

  static final EspBlufi _instance = EspBlufi._();

  static EspBlufi get instance => _instance;

  void onMessageReceived(EspBlufiListener listener) {
    methodChannel.setMethodCallHandler((call) async {
      debugPrint(call.toString());
      if (call.method == "scanResult") {
        debugPrint(call.arguments);
        if (listener.onScanResult != null) {
          listener.onScanResult!(EspDevice.fromJson(call.arguments));
        }
      } else if (call.method == "connectDevice") {
        if (listener.onConnectResult != null) {
          listener.onConnectResult!(call.arguments);
        }
      } else if (call.method == "deviceStatus") {
        if (listener.onDeviceStatus != null) {
          listener.onDeviceStatus!(call.arguments);
        }
      } else if (call.method == "scanWifi") {
        if (listener.onScanWifi != null && (call.arguments is List)) {
          listener
              .onScanWifi!(List.generate(call.arguments.length, (index) => DeviceWifi.fromJson(call.arguments[index])));
        }
      }
    });
  }

  Future<bool> scan({String filter = "BLUFI"}) async {
    bool result = await methodChannel.invokeMethod("scan", {"filter": filter}).catchError((error) {
      debugPrint(error.toString());
      return false;
    });
    return result;
  }

  void stopScan() {
    methodChannel.invokeMethod("stopScan");
  }

  void connectDevice(String address) {
    methodChannel.invokeMethod("connectDevice", {"address": address});
  }

  void configure(String ssid, String password) {
    methodChannel.invokeMethod("configure", {
      "ssid": ssid,
      "password": password,
    });
  }

  void requestDeviceWifiScan() {
    methodChannel.invokeMethod("requestDeviceWifiScan");
  }

  void requestDeviceVersion() {
    methodChannel.invokeMethod("requestDeviceVersion");
  }

  void requestDeviceStatus() {
    methodChannel.invokeMethod("requestDeviceStatus");
  }

  void requestCloseConnection() {
    methodChannel.invokeMethod("requestCloseConnection");
  }

  ///判断蓝牙开关
  Future<bool> isBluetoothEnabled()async{
    return await methodChannel.invokeMethod("isBluetoothEnabled");
  }
}

class EspBlufiListener {
  void Function(EspDevice device)? onScanResult;
  void Function(dynamic connectResult)? onConnectResult;
  ///配网和获取设备状态都是通过这个接收
  void Function(DeviceStatus deviceStatus)? onDeviceStatus;
  void Function(List<DeviceWifi> wifiList)? onScanWifi;

  EspBlufiListener({this.onScanResult, this.onConnectResult, this.onDeviceStatus, this.onScanWifi});
}
